<?php
/**
 * Author: 式神(vashi)
 * email: 289650682@qq.com
 * Date: 2019/1/25 13:29
 * FileName: Rule.php
 */

namespace app\common\model;


use think\Db;
use think\model\Pivot;

class RoleGroup extends Pivot
{
    protected $tip_name = '角色';
    protected $validate;
    protected $table;
    protected $res=[
        'code'=>3,
        'msg'=>'验证失败'
    ];
    public function initialize()
    {
        parent::initialize();
        $this->table=config('database.prefix').'auth_group_access';
    }

    //添加规则
    public function access($input){
        if(isset($input['group_id'])){
            $group_id=array_unique($input['group_id']);
        }else{
            $group_id=[];
        }
        $uid=$input['uid'];
        Db::startTrans();
        try{
            $this->where('uid',$uid)->delete();
            if(count($group_id)>0){
                $data = [];
                $num=0;
                foreach ($group_id as $d){
                    $data[$num]=[
                        'uid'=>$uid,
                        'group_id'=>$d
                    ];
                    $num++;
                }
                $this->saveAll($data);
            }
            // 提交事务
            Db::commit();
            $this->res['code']=0;
            $this->res['msg']='授权成功！';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->res['msg']='授权失败,请重试！';
        }

        return $this->res;
    }
}